import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:flutter/material.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:date_format/date_format.dart';

class GuaranteePage extends StatefulWidget {
  // GuaranteePage({Key key, this.title}) : super(key: key);

  // final String title;
  final String oid;
  GuaranteePage(this.oid);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid);
}

class _MyHomePageState extends State<GuaranteePage> {
  final String oid;
  _MyHomePageState(this.oid);
  TextEditingController _nametroller = new TextEditingController();
  TextEditingController _address = new TextEditingController();
  TextEditingController _mobiletroller = new TextEditingController();
  TextEditingController _pricetroller = new TextEditingController();
  TextEditingController _idcardtroller = new TextEditingController();
  TextEditingController _expricetroller = new TextEditingController();
  TextEditingController _passtroller = new TextEditingController();
  TextEditingController _confirmpasstroller = new TextEditingController();
  List formList;
  bool agreen = false;
  File _image;
  String card_z = '';
  String card_f = '';
  bool select_img = false;
  initState() {
    super.initState();
    // formList = [
    //   {
    //     "title": '车牌号',
    //     'sub_title': '云A00001',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 1,
    //     'bottom': 1.0,
    //     'value': '',
    //     'code': ''
    //   },
    //   {
    //     "title": '上牌日期',
    //     'sub_title': '云A00001',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 2,
    //     'bottom': 1.0,
    //     'value': '请选择日期',
    //     'code': ''
    //   },
    //   {
    //     "title": '里程数',
    //     'sub_title': '云A00001',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 1,
    //     'bottom': 1.0,
    //     'value': '',
    //     'code': ''
    //   },
    //   {
    //     "title": '车价',
    //     'sub_title': '云A00001云A00001云A00',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 1,
    //     'bottom': 10.0,
    //     'value': '',
    //     'code': ''
    //   },
    //   {
    //     "title": '投保人',
    //     'sub_title': '云A00001云A00001云A00',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 1,
    //     'bottom': 1.0,
    //     'value': '',
    //     'code': ''
    //   },
    //   {
    //     "title": '联系电话',
    //     'sub_title': '云A00001云A00001云A00',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 1,
    //     'bottom': 10.0,
    //     'value': '',
    //     'code': ''
    //   },
    //   {
    //     "title": '品牌',
    //     'sub_title': '云A00001云A00001云A00',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 3,
    //     'bottom': 1.0,
    //     'value': '请选择品牌',
    //     'code': '',
    //     'brand_id':'',

    //   },
    //   {
    //     "title": '车型',
    //     'sub_title': '云A00001云A00001云A00',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 3,
    //     'bottom': 10.0,
    //     'value': '请选择车型',
    //     'code': '',
    //     'type_id':''
    //   },
    //   {
    //     "title": '行驶证',
    //     'sub_title': '云A00001云A00001云A00',
    //     'sub_color': Color.fromRGBO(27, 182, 251, 1),
    //     'type': 4,
    //     'bottom': 10.0,
    //     'value': '',
    //     'code': ''
    //   },
    // ];
    formList = [
      {
        "title": '姓名',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'name',
        'ctr': _nametroller
      },
      {
        "title": '联系电话',
        'sub_title': 'phone',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'phone',
        'ctr': _mobiletroller
      },
      {
        "title": '地址',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 1.0,
        'value': '',
        'code': 'address',
        'ctr': _address
      },
      // {
      //   "title": '车价',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
      // {
      //   "title": '投保人',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 1.0,
      //   'value': '',
      //   'code': ''
      // },
      // {
      //   "title": '联系电话',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 1,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
      // {
      //   "title": '品牌',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 3,
      //   'bottom': 1.0,
      //   'value': '请选择品牌',
      //   'code': '',
      //   'brand_id': '',
      // },
      // {
      //   "title": '车型',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 3,
      //   'bottom': 10.0,
      //   'value': '请选择车型',
      //   'code': '',
      //   'type_id': ''
      // },
      {
        "title": '车价（万）',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': 1,
        'bottom': 10.0,
        'value': '',
        'code': 'carPirce',
        'ctr': _pricetroller
      },
      // {
      //   "title": '行驶证',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': 4,
      //   'bottom': 10.0,
      //   'value': '',
      //   'code': ''
      // },
    ];
  }

  Widget layout() {
    List<Widget> tiles = [];
    Widget content;
    for (var item in formList) {
      var type = item["type"];
      if (type == 1) {
        //输入框
        tiles.add(inputWidget(item));
      } else if (type == 2) {
        //时间选择
        tiles.add(dateSelect(item));
      } else if (type == 3) {
        //类型选择
        tiles.add(cartype(item));
      } else if (type == 4) {
        //图片
        tiles.add(imagUp(item));
      }
    }
    // var btn = new SizedBox(
    //     width: double.infinity,
    //     height: 50,
    //     child: new FlatButton(
    //       child: Text('立即申请入驻'),
    //       textColor: Colors.white,
    //       color: Colors.white,
    //       //color: Color.fromRGBO(27, 182, 251, 1),
    //       onPressed: () {
    //         regist();
    //       },
    //     ));
    var btn = new Container(
        color: Color.fromRGBO(239, 239, 239, 1),
        //color:Colors.white,
        child: new Padding(
            padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
            child: new Material(
              color: Color.fromRGBO(239, 239, 239, 1),
              //INK可以实现装饰容器
              child: new Ink(
                //用ink圆角矩形
                //color: Color.fromRGBO(239, 239, 239, 1),
                decoration: new BoxDecoration(
                  //背景

                  color: Color.fromRGBO(255, 204, 48, 1),
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(18.0)),
                  //设置四周边框
                  border: new Border.all(
                      width: 1, color: Color.fromRGBO(255, 204, 48, 1)),
                ),
                child: new InkWell(

                    //圆角设置,给水波纹也设置同样的圆角
                    //如果这里不设置就会出现矩形的水波纹效果
                    borderRadius: new BorderRadius.circular(15.0),
                    //设置点击事件回调
                    onTap: () {
                      submit();
                    },
                    child: Container(
                      //设置 child 居中
                      alignment: Alignment(0, 0),
                      height: 36,
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      width: double.infinity,
                      child: Text(
                        "提    交",
                        style: TextStyle(color: Colors.white),
                      ),
                    )),
              ),
            )));
    tiles.add(btn);
    content = new Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
        child: new Column(
            children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
            //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
            ));
    return content;
  }

//提交保修
  submit() async {
    FocusScope.of(context).requestFocus(FocusNode());
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    print(this.formList);
    Map<String, String> param = new Map();
    for (var i = 0; i < this.formList.length; i++) {
      var item = this.formList[i];
      if (item["code"] != "") {
        var code = item["code"];
        if (item["value"] == "") {
          Toast.show('请填写完整的信息', context);
          return;
          // break;
        }
        param[code] = item["value"].toString();
      }
    }
    //param['']
    // param["brand_id"] = formList[3]["brand_id"];
    // param["brand_string"] = formList[3]["value"];
    // param["cartype_id"] = formList[4]["type_id"];
    // param["cartype_string"] = formList[4]["value"];
   // param["car_id"] = "0";
    param["car_id"] = this.oid;

    SharedPreferences pref = await SharedPreferences.getInstance();

    param["bid"] = pref.getString('uid');
    param["price"] = "1500";
    print(param);

    HttpHelper.post(HttpHelper.API_Guratee, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["status"].toString() == "1") {
          Toast.show(data["result"]["message"], context);
          //清空输入框
          // _nametroller.clear();
          // _mobiletroller.clear();
          // _address.clear();
          // _pricetroller.clear();
          // for (var i = 0; i < this.formList.length; i++) {
          //   var item = this.formList[i];
          //   item["value"] = "";
          // }
          // formList[3]["brand_id"] = "";
          // formList[3]["value"] = "请选择品牌";
          // formList[4]["type_id"] = "";
          // formList[4]["value"] = "请选择车型";
          // setState(() {
          //   formList = formList;
          // });
        }
      }
    }, params: param);
  }

  //输入框组件
  Widget inputWidget(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: new TextField(
                      controller: item["ctr"],
                      textAlign: TextAlign.right,
                      // controller: _nametroller,
                      decoration: InputDecoration(
                        hintText: '请输入' + item["title"],
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                        ),
                      ),
                      onChanged: (val) {
                        print(val);
                        item["value"] = val;
                      },
                    )),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //日期选择组件
  Widget dateSelect(item) {
    DateTime initialDate = DateTime.now();
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 50,
          child: new Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: RichText(
                    text: TextSpan(
                        text: item["title"],
                        style: TextStyle(
                            fontSize: 15,
                            color: Color.fromRGBO(102, 102, 102, 1)),
                        children: [
                          // TextSpan(
                          //     text: '*',
                          //     style: TextStyle(fontSize: 14, color: Colors.red))
                        ]),
                  ),
                ),
                flex: 1,
              ),
              Expanded(
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                    child: Align(
                        alignment: Alignment.centerRight,
                        child: new GestureDetector(
                            child: new Text(item["value"]),
                            onTap: () async {
                              final DateTime dateTime = await showDatePicker(
                                context: context,
                                //定义控件打开时默认选择日期
                                initialDate: initialDate,
                                //��义控件最早可以选择的日期
                                firstDate: DateTime(2018, 1),
                                //定义控件最晚可以选择的日期
                                lastDate: DateTime(2050, 1),
                              );

                              if (dateTime != null) {
                                setState(() {
                                  String code = item["code"];
                                  item["value"] = formatDate(
                                      dateTime, [yyyy, "-", mm, "-", dd]);
                                  //formalities[code] = item["value"];
                                });
                              }
                            }))),
                flex: 2,
              )
            ],
          ),
        ));
    return content;
  }

  //车辆类型组件
  Widget cartype(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
            color: Colors.white,
            height: 50,
            child: new GestureDetector(
              onTap: () {
                // print('选择车型');
                // Navigator.pushNamed(context, 'brand');
                if (item.containsKey("brand_id")) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandSelectRoute(item);
                  }));
                } else {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new CartypeSelectRoute(
                        item, formList[3]["brand_id"]);
                  }));
                }
              },
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    child: new Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: RichText(
                        text: TextSpan(
                            text: item["title"],
                            style: TextStyle(
                                fontSize: 15,
                                color: Color.fromRGBO(102, 102, 102, 1)),
                            children: [
                              // TextSpan(
                              //     text: '*',
                              //     style: TextStyle(fontSize: 14, color: Colors.red))
                            ]),
                      ),
                    ),
                  ),
                  //  Expanded(
                  //   child:
                  new Padding(
                    padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                    child: RichText(
                      text: TextSpan(
                          text: item["value"],
                          style: TextStyle(
                              fontSize: 15,
                              color: Color.fromRGBO(102, 102, 102, 1)),
                          children: [
                            // TextSpan(
                            //     text: '*',
                            //     style: TextStyle(fontSize: 14, color: Colors.red))
                          ]),
                    ),
                  ),

                  //),
                  // Expanded(
                  //   child:
                  Padding(
                      padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                      child: Align(
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            'resource/images/user/detail.png',
                            height: 20,
                          ))),

                  // )
                ],
              ),
            )));
    return content;
  }

  //图片上传组件
  Widget imagUp(item) {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, item["bottom"]),
        child: Container(
          color: Colors.white,
          height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: item["title"],
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                    color: Colors.white,
                    height: 100,
                    child: new Row(
                      children: <Widget>[
                        Expanded(
                            child: new Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 10, 10),
                              child: new GestureDetector(
                                  onTap: () {
                                    getImage(1);
                                  },
                                  child:card_z==""? Image.asset("resource/images/user/upimg.png"):CachedNetworkImage(imageUrl: card_z)
                                  // FadeInImage.assetNetwork(
                                  //   placeholder:
                                  //       "resource/images/user/upimg.png",
                                  //   image: card_z,
                                  // )
                                  ),
                              // new Image.asset('resource/images/user/card_img1.png'),
                            ),
                            flex: 1),
                        Expanded(
                            child: new Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 10, 10),
                              child: new GestureDetector(
                                  onTap: () {
                                    getImage(2);
                                  },
                                  child: 
                                  card_f==""? Image.asset("resource/images/user/upimg.png"):CachedNetworkImage(imageUrl: card_f)
                                  // FadeInImage.assetNetwork(
                                  //   placeholder:
                                  //       "resource/images/user/upimg.png",
                                  //   image: card_f,
                                  // )
                                  ),
                              // new Image.asset('resource/images/user/card_img2.png'),
                            ),
                            flex: 1),
                      ],
                    ),
                  )),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

//发送验证码
  sendcode() {
    print('获取验证码');
    if (_mobiletroller.text.trim().length == 0) {
      Toast.show("填写手机号", context);
      return;
    }
    Map<String, String> map = new Map();
    map["mobile"] = _mobiletroller.text.trim();
    HttpHelper.post(HttpHelper.API_SendCode, (data) {
      if (data != null) {
        print(data);
        Toast.show(data["result"]["message"], context);

        if (data["status"].toString() == "0") {
          // Navigator.pop(context);

          setState(() {
            // orderInfo=data["data"];
          });
        }
      }
    }, params: map);
  }

  //选择图片
  getimgs(type, card) async {
    if (type == 1) {
      var image = await ImagePicker.pickImage(source: ImageSource.gallery);

      setState(() {
        _image = image;
        select_img = true;
      });
    } else {
      var image = await ImagePicker.pickImage(source: ImageSource.camera);

      setState(() {
        _image = image;
        select_img = true;
      });
    }
    if (_image == null) return;
    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_image, (data) {
      if (card == 1) {
        setState(() {
          card_z = data["url"];
        });
      } else {
        card_f = data["url"];
      }
    }, params: map);
  }

//选择图片�����
  Future getImage(type) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return new SimpleDialog(
            title: new Text('选择'),
            children: <Widget>[
              new SimpleDialogOption(
                child: new Text('相机'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(0, type);
                },
              ),
              new SimpleDialogOption(
                child: new Text('相册'),
                onPressed: () {
                  Navigator.pop(context);
                  getimgs(1, type);
                },
              )
            ],
          );
        });
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    // //_upLoadImage(image);//上传图片
    // setState(() {
    //   _image = image;
    // });
  }

  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('保修'),
          backgroundColor: Colors.white,
          elevation: 0,
          // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
        ),
        body: new Center(
            child: Container(
                decoration: new BoxDecoration(
                  color: Color.fromRGBO(238, 238, 238, 1),
                ),
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
                    child: Stack(
                      children: <Widget>[
                        Align(
                          alignment: Alignment.topCenter,
                          child: new ListView(children: <Widget>[layout()]),
                        ),
                        Align(
                            // alignment: Alignment.bottomLeft,
                            // child: SizedBox(
                            //   width: double.infinity,
                            //   height: 50,
                            //   child: new Container(
                            //    // color: Colors.red,
                            //     child: Padding(
                            //       padding: new EdgeInsets.fromLTRB(15, 0, 15, 0),
                            //       child: Padding(
                            //         padding:
                            //             new EdgeInsets.fromLTRB(10, 10, 10, 40),
                            //         child: new SizedBox(

                            //             width: double.infinity,
                            //             height: 50,
                            //             child: new RaisedButton(
                            //               child: Text('立即申请入驻'),
                            //               textColor: Colors.white,
                            //               color: Colors.white,
                            //               //color: Color.fromRGBO(27, 182, 251, 1),
                            //               onPressed: () {
                            //                 regist();
                            //               },
                            //             )),
                            //       ),
                            //     ),

                            //   ),
                            // ),
                            )
                      ],
                    )
                    // new ListView(
                    //   children: <Widget>[buildcontent()],
                    // )),
                    ))));
  }
}
